package com.itheima.wechat;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.JedisUtl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    JedisUtl jedisUtl;
    @Reference
    MemberService memberService;
    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletRequest request) {
        String telephone = (String)map.get("telephone");
        String validateCode = (String)map.get("validateCode");
        //校验验证码
        String redisCode = jedisUtl.get(telephone + RedisConstant.SMs_CODE_KEY_LOGIN);
        if (redisCode == null || !redisCode.equals(validateCode)) {
            return Result.ERROR("验证码输入错误");
        }
        //根据手机号码查询是否是我们的会员
         Member member = memberService.findDyTelephone(telephone);
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);//在这里不能拿到会员id
        }
        //存储用户的登录状态
       // request.getSession().setAttribute("memeber", member);
        //把用户的登录状态保存到redis
        String token = UUID.randomUUID().toString() + member.getId();//保证token不重复
        //JSON.toJSONString(memeber) 把会员信息转为json字符串存到redis，也可以使用redis里面的hash数据格式
        jedisUtl.setex(token, 60 * 60 * 24 * 15, JSON.toJSONString(member));

        return Result.OK("",token);//token返回页面保存，下次发请求需要带上，后端需要去redis校验
    }
}
